(function () {

	// implement JSON.stringify serialization
	// Prototype.js overloads window.JSON with a buggy implementation
	Backbone.JSON = {};
	Backbone.JSON.stringify = function (obj) {
		var t = typeof (obj);
		if (t != "object" || obj === null) {
			// simple data type
			if (t == "string") obj = '"'+obj+'"';
			return String(obj);
		}
		else {
			// recursive array or object
			var n, v, json = [], arr = (obj && obj.constructor == Array);
			_.each(obj, function(v, n) {
				t = typeof(v);
				if (t == "string") v = '"'+v.replace(/\n/g, '\\n')+'"';
				else if (t == "object" && v !== null) v = Backbone.JSON.stringify(v);
				json.push((arr ? "" : '"' + n + '":') + String(v));
			});
			return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
		}
	};

    var methodMap = {
        'create':'POST',
        'update':'PUT',
        'delete':'DELETE',
        'read':'GET'
    };

    Backbone.sync = function (method, model, options) {
        var type = methodMap[method];

        var request = {
            req:model.requestMap[method],
            data: _.extend({
                user:localStorage.getItem("yast_user"),
                hash:localStorage.getItem("yast_hash")
            }, options.data ? options.data : {})
        };

        if (type != "GET") {
            request.data.objects = {};
			var name = '';
			if(model instanceof window.Yast.models.classes.Record)
				name = 'record';
			else if(model instanceof window.Yast.models.classes.Folder)
				name = 'folder';
			else if(model instanceof window.Yast.models.classes.Project)
				name = 'project';

            request.data.objects[name] = model.toJSON();
        }

        // Default JSON-request options.
        var params = _.extend({
            type: 'GET',
            dataType:'json',
            url:"http://www.yast.com/1.0/?lang=javascript&jsonp=?&request=" + encodeURIComponent(Backbone.JSON.stringify(request))
        }, options);

        // Ensure that we have a URL.
        if (!params.url) {
            params.url = getUrl(model) || urlError();
        }

		// Wrap error
		var fnOrgError = params.error;
		params.error = function(a, b, c){
			if(fnOrgError){
				fnOrgError(a, b, c);
			}
			// Push a global app event
// 			window.Yast.vent.trigger('apiError');
		}

		// Wrap success() to check for errors manually
		var fnSuccess = params.success;
		params.success = function(resp, status, xhr){
			if(resp.status == 0){
				fnSuccess(resp, status, xhr);
			}else{
				// Call error function
				var fnError = Backbone.wrapError(params.error, this, params);
 				fnError(xhr, 'error');
			}
		}


        // Make the request.
        return jQuery.ajax(params);
    };

}).call(this);


